
# -*- coding: utf-8 -*-

import urllib.request
import requests
from bs4 import BeautifulSoup
from FFXIVfirstSearch import firstSearch

class iterableSearch(object):
    def __init__(self, *args, **kwargs):
        return super().__init__(*args, **kwargs)

    def __searchItem(self,itemName,itemDict,itemNum=1):
        target="https://ff14.huijiwiki.com/wiki/%E7%89%A9%E5%93%81:"+itemName
        req=requests.get(url=target)
        html=req.text
        bf=BeautifulSoup(html)
        texts=bf.find_all('table',class_='wikitable item-craft-table filter-div--item')
        if texts==[]:
            return
        texts2=BeautifulSoup(str(texts[0]))
        b_1=texts2.find_all('ul',class_='item-craft-list')
        b_2=BeautifulSoup(str(b_1[0]),parse_only=None)
        tag=b_2.li.ul
        for temp in tag.previous_sibling.stripped_strings:
            print(temp)
            if '×' in temp:
                print("temp:",temp)
                outNum=int(temp[1:])
                if int(itemNum)%outNum!=0:
                    itemNum=int(itemNum)-int(itemNum)%outNum+outNum
            else: outNum=1
        tempList=list()
        for child in tag.children:
            for string in child.div.stripped_strings:
                if '[' in string or '/' in string or ']' in string:
                    pass
                else: tempList.append(string)
            tempList[1]=tempList[1][1:]
            numInDict=itemDict.get(tempList[0],['0'])
            print(tempList[0],"numInDict:%s"%numInDict[0])
            tempList[1]=int(int(tempList[1])*int(itemNum)/outNum+int(numInDict[0]))
            itemDict[tempList[0]]=list(tempList[1:])
            if len(itemDict[tempList[0]])>1:
                if '园' not in itemDict[tempList[0]][1] and '矿' not in itemDict[tempList[0]][1]:
                    self.__searchItem(tempList[0],itemDict,int(tempList[1]))
            tempList.clear()
        del itemDict[itemName]
        print(itemDict)
        print('\n\n')
        return itemDict

    def work(self,itemDict):
        itemNameList=list(itemDict.keys())
        for each in itemNameList:
            print("迭代：",each)
            if each in itemDict:
                print(itemDict[each])
                if len(itemDict[each])>1:
                    if '园' not in itemDict[each][1] and '矿' not in itemDict[each][1]:
                        self.__searchItem(each,itemDict,itemDict[each][0])
            else:
                print("已搜索")
        return itemDict



if __name__ == '__main__':
    a=firstSearch()
    fResult=a.work('灵银制敌头盔')
    
    print("----------------------------------------------------------------------------\n\n")
    
    #fResult={'水之晶簇': ['1'], '纯净水': ['9'], '稀硫酸': ['1']}
    b=iterableSearch()
    iResult=b.work(fResult)
    print(iResult)
    